#include "queueArea.h"

queueArea::queueArea(QWidget *parent)
		: QScrollArea(parent),
		dontClearQueue(false),
		totalSize_(0)
{ }

void queueArea::addPreview(PreviewWidget* preview) {
	this->widget()->layout()->addWidget(preview);
	allPreviews.append(preview);
	preview->setListPosition(allPreviews.indexOf(preview));
	connect(preview, SIGNAL(removeMe(PreviewWidget*)), this, SLOT(removePreview(PreviewWidget*)));
	totalSize_ += preview->size();
	emit isEmpty(false);
}


void queueArea::clearQueue() {
	foreach(PreviewWidget* preview, allPreviews) {
		this->widget()->layout()->removeWidget(preview);
		allPreviews.removeAll(preview);
		preview->deleteLater();
	}
	totalSize_ = 0;
	if (allPreviews.count() == 0) {
		emit isEmpty(true);
	}
}

void queueArea::setProgress(const int val, const int max, const int index) {
	allPreviews.at(index)->setProgress(val, max);
}

void queueArea::removeFinished() {
	if ( !dontClearQueue ) {
		foreach (PreviewWidget *preview, allPreviews) {
			if ( preview->toDelete() ) {
				totalSize_ -= preview->size();
				this->widget()->layout()->removeWidget(preview);
				allPreviews.removeAll(preview);
				preview->deleteLater();
			}
		}
	}
	if (allPreviews.count() == 0) {
		emit isEmpty(true);
	}
}

QList<ImageToUpload> queueArea::ImagesToUpload() {
	QList<ImageToUpload> ret;
	foreach (PreviewWidget *preview, allPreviews) {
		ret.append(preview->image());
	}
	return ret;
}

void queueArea::lockRemoveButtons() {
	foreach ( PreviewWidget *preview, allPreviews ) {
		preview->disableRemoveButton();
	}
}

void queueArea::unlockRemoveButtons() {
	foreach ( PreviewWidget *preview, allPreviews ) {
		preview->enableRemoveButton();
	}
}

void queueArea::setUploadError(const int index, const QString &string) {
	allPreviews.at(index)->uploadError(string);
}

#ifndef NOPREVIEW
const QPixmap* queueArea::previewPxm(const int index) const {
	return allPreviews.at(index)->previewPxm();
}
#endif //NOPREVIEW

void queueArea::setToDelete(const int index, const bool delete_) {
	allPreviews.at(index)->setToDelete(delete_);
}

void queueArea::started(const int index) {
	allPreviews.at(index)->uploadStarted();
}

void queueArea::finished(const int index) {
	allPreviews.at(index)->uploadFinished();
}

void queueArea::removePreview(PreviewWidget *widget) {
	allPreviews.removeAll(widget);
	if (allPreviews.count() == 0) {
		emit isEmpty(true);
	}
}

qint64 queueArea::lastDelta(const int index) const {
	return allPreviews.at(index)->lastDelta();
}
